package kino.net;

import kino.common.KinoConstant;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CommandEncoder {

    public String encode(Object o) {
        if (o instanceof String) {
            return stringEncode((String)o);
        } else if (o instanceof Integer) {
            return integerEncode((Integer)o);
        } else if (o instanceof List) {
            return listEncode((List)o);
        }
        return o.toString();
    }

    public String error(String err) {
        return "-ERR" + err + KinoConstant.crlf;
    }

    public boolean isErrorMsg(String msg) {
        return msg.startsWith("-");
    }
    public String simpleStringEncode(String o) {
        return "+" + o + KinoConstant.crlf;
    }
    public String stringEncode(String o) {
        return "$" + o.getBytes().length + KinoConstant.crlf + o + KinoConstant.crlf;
    }
    public String integerEncode(Integer o) {
        return ":" + o + KinoConstant.crlf;
    }

    public String listEncode(List o) {
//        if (o.size() == 0) {
//            return KinoConstant.NIL;
//        }
        StringBuffer encodeStr = new StringBuffer();
        encodeStr.append("*").append(o.size()).append(KinoConstant.crlf);
        o.forEach(item -> {
            if (item instanceof String) {
                encodeStr.append(stringEncode((String)item));
            } else if (item instanceof Integer) {
                encodeStr.append(integerEncode((Integer)item));
            } else if (item instanceof List) {
                encodeStr.append(listEncode((List)item));
            }
        });
        return encodeStr.toString();
    }
}
